#!/bin/bash

## Remove dir of not last day each month of year, 
## Arg one is the directory to scan
## Arg two is sure for really remove
## DO NOT WITH SURE before check the remove is right

## Last day of Every month to remove
##
remaindir=(0131 0228 0331 0430 0531 0630 0731 0830 0930 1031 1130 1231)

## I don't know how to use , so ignore it
dir_will_remove=()

## Set 1 to print more
DEBUG=0

## Arges with second sure will really remove
SURE_REMOVE=0

function logd() {
	if [ $DEBUG -eq 1 ]; then
		echo "$*"
	fi
}

function log() {
	echo "$*"
}

if [ $# -lt 1 ]; then
	log "Usage: $0 dirpath [sure](for really remove, becarefull)"
	exit
fi

function do_remove() {
	log "do remove dir $1"
	dir=$1
	year=$2
	let i=0
	for i in `ls $dir`
	do
		## dir is 10 characters
		if [ ! ${#i} -eq 10 ]; then
			continue
		fi

		for j in `ls $dir/$i`
		do
			fulldir=$dir/$i/$j
			odir=$j
			logd "check dir $odir"

			## check year equal
			prefix=${odir:0:4}
			if [ $prefix != $year ]; then
				continue
			fi

			## Find all remain dir, find if need remain
			remove_flag=1
			for rem in ${remaindir[@]}
			do
				logd "check preifx $prefix and year $year"
				logd "check dir $prefix$rem and $odir"
				if [ "$prefix$rem" == "$odir" ]; then
					logd "## ## remain it $odir"
					remove_flag=0
				fi
			done

			## find
			if [ "$remove_flag" == "1" ]; then
				log "** ** will add $fulldir to remove, this line for make sure it is right"
				if [ $SURE_REMOVE -eq 1 ]; then
					log "---- do remove $fulldir , will this line, it means the directory really removed"
					rm -rf $fulldir
				fi
			fi
		done
	done
}

function debug_print() {
	for i in ${dir_will_remove[@]}
	do
		log "will remove $i"
	done
}

read -p "Give me the year to remove " year

if [ "$2" == "sure" ]; then
	SURE_REMOVE=1
fi

do_remove $1 $year

debug_print

